package com.itcast.hotel.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.hotel.mapper.HotelMapper;
import com.itcast.hotel.pojo.Hotel;
import com.itcast.hotel.pojo.HotelDoc;
import com.itcast.hotel.pojo.PageResult;
import com.itcast.hotel.pojo.RequestParams;
import com.itcast.hotel.service.HotelService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 29143
 */
@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        //创建请求对象
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        buildBasicQuery(params, source);
        //构建分页参数
        Integer page = params.getPage();//页码
        Integer size = params.getSize();// 每页条数
        source.from((page - 1) * size);
        source.size(size);

        //调用client执行请求
        return handleResult(request);
    }

    /**
     * 封装查询条件
     *
     * @param params
     * @param source
     */
    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {

        //创建BoolQueryBuilder对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //构建关键词key match搜索 must 算分
        String key = params.getKey();
        System.out.println(key);
        //判断前端传过来的key是否为空
        if (StringUtils.isNotBlank(key)) {
            //当前端传过来的key不为空时,就根据所有字段查询包含key的数据
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
            //创建高亮显示对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //构建高亮三要素
            highlightBuilder.field("name");
            highlightBuilder.preTags("<font color='red'>");
            highlightBuilder.postTags("</font>");
//            highlightBuilder.preTags("<span style='color : red'>");
//            highlightBuilder.postTags("</span>");
            //关闭字段匹配检查
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
        } else {
            //当前端传过来的key为空时,就查询所有数据
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        //构建城市city term搜索
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }

        //构建品牌 brand term搜索
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        //构建星级 starName term搜索
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }

        //构建价格范围 range搜索
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        //构建地理位置 location geo搜索
        String location = params.getLocation();
        if (StringUtils.isNotBlank(location)) {
            source.sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)).order(SortOrder.ASC) //距离升序
                    .unit(DistanceUnit.KILOMETERS)); //单位km
        }

        //算分查询条件
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder, //原来的条件
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", "true"),//代表打广告的酒店
                        ScoreFunctionBuilders.weightFactorFunction(10)//设置分数
                )}).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY); //设置加权方式: 相乘

        source.query(functionScoreQuery);
    }


    /**
     * 抽取结果处理的代码
     *
     * @param request
     * @return
     */
    private PageResult handleResult(SearchRequest request) {

        try {
            //执行请求得到响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应结果
            SearchHits searchHits = response.getHits();
            //查询总数量
            long total = searchHits.getTotalHits().value;
            //创建一个list集合
            List<HotelDoc> list = new ArrayList<>();
            //按照kibana的格式,解析结果
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                //获取文档内容json
                String docJson = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(docJson, HotelDoc.class);
                //单独获取高亮显示结果//定义一个map集合,用来获取高亮显示的结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    HighlightField name = highlightFields.get("name");
                    String s = name.getFragments()[0].toString();
                    hotelDoc.setName(s);
                }
                //获取sort排序的字段值
                Object[] values = hit.getSortValues();
                if (values != null && values.length > 0) {
                    //设置距离
                    hotelDoc.setDistance(values[0]);
                }
                list.add(hotelDoc);
            }
            //封装结果并返回
            return new PageResult(total, list);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //创建请求对象
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            buildBasicQuery(params, source);
            //设置size
            source.size(0);
            //调用聚合方法
            buildAggregation(source);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String,List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //根据品牌名称,获取品牌结果,并添加到map集合当中
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand",brandAgg);
            //根据城市名称,获取城市结果,并添加到map集合当中
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            result.put("city",cityAgg);
            //根据星级名称,获取星级结果,并添加到map集合当中
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            result.put("starName",starAgg);

            return result;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public List<String> getSuggestions(String key) {

            //创建请求对象
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            //准备DSL
            source.suggest(new SuggestBuilder().addSuggestion(
                    "mySuggestion", SuggestBuilders.completionSuggestion("suggestion")
                    .prefix(key)
                    .skipDuplicates(true)
                    .size(10)
            ));
        try {
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称,获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("mySuggestion");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历
            List <String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }

            return list;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }


    /**
     * 定义一个聚合方法
     * 构建聚合条件
     *
     * @param source
     */
    private void buildAggregation(SearchSourceBuilder source) {
        //设置根据品牌进行分组
        source.aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));

        //设置根据城市进行分组
        source.aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));

        //设置根据星级进行分组
        source.aggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //创建一个List集合,用来接收key
        List<String> brandList = new ArrayList<>();
        //遍历集合
        for (Terms.Bucket bucket : buckets) {
            //获取key,并封装到list当中
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        //返回list集合
        return brandList;
    }




    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("hotel",String.valueOf(id));
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void insertById(Long id) {
        try {
        //根据id查询酒店数据
        Hotel byId = getById(id);
        //转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(byId);
        //创建请求对象
        IndexRequest request = new IndexRequest("hotel");
        request.id(String.valueOf(id));
        //准备JSON文档
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //发送请求
        client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }
}
